<script lang="ts" setup>
defineOptions({
  name: "ArticleDetail",
});
import { isEmptyObject } from "@/assets/js/types";
import { set_progress_ratio } from "@/components/common/HomeScrollSnap/store";
import { pxChangeRem } from "@/utils";
import { fetchArticleList } from "../home/store";
import { classNameArticleDetailItem } from "@/config/const_var";
let isFixed = ref(false);
let overflowY = ref("hidden");
let articleDetailItemRef = ref<any>(null);
let observerDetailItem = new IntersectionObserver((entries) => {
  entries.forEach(async (entry) => {
    if (entry.isIntersecting === true) {
      overflowY.value = "hidden";
      isFixed.value = false;
    }
    if (entry.isIntersecting === false) {
      overflowY.value = "scroll";
      isFixed.value = true;
    }
  });
});
let observerDetailList = new IntersectionObserver((entries) => {
  entries.forEach(async (entry: any) => {
    let target = entry.target;
    if (entry.isIntersecting === true) {
      let index = target.dataset.index * 1;
      let exposureTimes = target.getAttribute("exposure-times");
      if (isEmptyType(exposureTimes)) {
        target.setAttribute("exposure-times", 1);
      }
      if (!isEmptyType(exposureTimes)) {
        return;
      }
      if (index % (remainingViewData.value.length - 2) === 0 && index != 0) {
        fetchDetailList();
      }
    }
  });
});

function handleItemListScrollY(event: { target: any }) {
  let target: any = event.target;
  let scrollTop = target.scrollTop;
  if (scrollTop > 10) {
    scrollSnapType.value = "y mandatory";
  } else {
    scrollSnapType.value = "none";
  }
}
function bindHomeItemListScrollY() {
  homeItemListRef.value.$el.addEventListener("scroll", handleItemListScrollY);
}
function removeHomeItemListScrollY() {
  homeItemListRef.value.$el.removeEventListener(
    "scroll",
    handleItemListScrollY
  );
}
let body = document.body;
function handleBodyScrollY(event: { target: any }) {
  let target = event.target;
  let scrollTop = target.scrollTop;
  let clientHeight = articleDetailItemRef.value.$el.clientHeight;
  set_progress_ratio(scrollTop, clientHeight);
}
function bindBodyScrollY() {
  body.addEventListener("scroll", handleBodyScrollY);
}
function removeBodyScrollY() {
  body.removeEventListener("scroll", handleBodyScrollY);
}

let totalViewData = ref<any>([]);
let firstViewData = ref<any>({});
let remainingViewData = ref<any>([]);
function scrollToTop() {
  let articleDetailItem = document.querySelector(
    `.${classNameArticleDetailItem}`
  );
  if (articleDetailItem) {
    articleDetailItem?.scrollIntoView({
      behavior: "instant",
    });
  } else {
    scrollElementTopUp();
  }
}
async function fetchDetailList() {
  let resData = await fetchArticleList();
  totalViewData.value = [...totalViewData.value, ...resData.data.rows];
  firstViewData.value = totalViewData.value[0];
  remainingViewData.value = totalViewData.value.slice(1);
  nextTick(() => {
    unobserveAllItems();
    observeAllItems();
    scrollToTop();
  });
}

function unobserveAllItems() {
  removeHomeItemListScrollY();
  observerDetailItem.unobserve(articleDetailItemRef.value.$el);

  [].forEach.call(homeItemListRef.value.$el.children, (element) => {
    observerDetailList.unobserve(element);
  });

  removeBodyScrollY();
}
function observeAllItems() {
  bindHomeItemListScrollY();
  observerDetailItem.observe(articleDetailItemRef.value.$el);

  [].forEach.call(homeItemListRef.value.$el.children, (element) => {
    observerDetailList.observe(element);
  });

  bindBodyScrollY();
}
onMounted(() => {
  fetchDetailList();
});
onBeforeRouteLeave(() => {
  unobserveAllItems();
});

let scrollSnapType = ref("none");
let homeItemListRef = ref<any>(null);
</script>
<template>
  <div class="article-detail">
    <ArticleDetailItem
      v-if="!isEmptyObject(firstViewData)"
      ref="articleDetailItemRef"
      v-model:content="firstViewData.content"
      v-model:item="firstViewData"
      class="pt-16 pr-16 pb-16 pl-16"
    />
    <HomeScrollXTabs v-model:is-fixed="isFixed" />
    <HomeItemList
      v-if="remainingViewData.length"
      class="pl-16 pr-16 pt-10"
      v-model:overflowY="overflowY"
      :paddingTop="isFixed ? pxChangeRem('50px') : '0px'"
      v-model:scrollSnapType="scrollSnapType"
      v-model:view-data="remainingViewData"
      ref="homeItemListRef"
    />
  </div>
</template>
<style lang="scss" scoped>
.article-detail {
  :deep(.#{$scss-classNameArticleDetailItem}) {
    scroll-margin: 0 0 100vh 0;
  }
}
</style>
